<template>
  <div class="app-container org business">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->

      <div>
        <p class="pinformation">搜索条件</p>
      </div>
      <el-form :model="queryParams" label-width="80">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名：" prop="nickName">
              <el-input clearable placeholder="请输入姓名" v-model="queryParams.nickName" maxlength="100"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色： ">
              <el-input clearable placeholder="请输入角色" v-model="queryParams.roleName" maxlength="100"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号：" prop="userName">
              <el-input clearable placeholder="请输入用户账号" v-model="queryParams.userName" maxlength="100"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前状态：" prop="workStatus">
              <el-select clearable v-model="queryParams.workStatus" placeholder="请选择当前状态">
                <el-option v-for="item in proxy.addListNoLimit(work_status)" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="员工编号：" prop="userCode">
              <el-input clearable placeholder="请输入员工编号" v-model="queryParams.userCode" maxlength="100"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row justify="end">
              <el-button type="success" @click="handleQuery">搜索</el-button>
              <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <!-- 机构列表 -->
      <div>
        <el-row style="justify-content: space-between">
          <el-row>
            <p class="pinformation">人员列表</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
          </el-row>
          <el-row style="margin-bottom: 5px">
            <el-button type="success" link icon="Plus" @click="addOrgId">新增</el-button>
          </el-row>
        </el-row>
        <el-table v-loading="loading" row-key="userId" ref="mainTableRef" :data="newUserTable"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @row-click="rowClick"
          :default-expand-all="true" :row-class-name="tableRowClass">
          <el-table-column prop="nickName" label="部门/用户" width="200">
            <template #default="scope">
              <svg-icon icon-class="user" style="margin-right: 5px" v-if="scope.row.userType" />
              <svg-icon icon-class="tree" style="margin-right: 5px" v-else />
              <span>{{ scope.row.nickName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="zw" label="职务" />
          <el-table-column prop="workStatus" label="状态">
            <template #default="scope">
              <span v-if="!scope.row.workStatus">在职</span>
              <span v-else>离职</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-tooltip content="重置密码" placement="top" v-if="scope.row.userType">
                <el-button link icon="Key" @click="resetPassword(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" v-if="scope.row.userType">
                <el-button link icon="Delete" @click="listhandleDelete(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 右侧分栏目 -->
    <el-card class="rightCard">
      <div style="position: relative">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-change="tabChange" :before-leave="leaveTab">
          <el-tab-pane label="基础信息" name="first">
            <div v-if="activeName == 'first'">
              <el-row style="margin-bottom: 5px">
                <el-col :span="18">
                  <p class="pinformation">个人信息</p>
                </el-col>
                <el-col :span="6">
                  <el-row justify="end">
                    <el-button type="success">导出信息表</el-button>
                    <el-button type="success" @click="addsava(false)">保存</el-button>
                  </el-row>
                </el-col>
              </el-row>

              <el-form :model="form" :rules="rules" ref="userRef" label-width="85px">
                <el-row>
                  <el-col :span="18">
                    <!-- 个人信息第一行 -->
                    <el-row>
                      <el-col :span="5">
                        <el-form-item label="姓名：" prop="nickName">
                          <el-input clearable placeholder="请输入姓名" v-model="form.nickName" maxlength="100" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="性别：" prop="sex">
                          <el-select clearable v-model="form.sex" placeholder="请选择性别">
                            <el-option v-for="item in sex" :key="item.value" :label="item.label" :value="item.value" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="员工编号：" prop="userCode">
                          <el-input clearable placeholder="请输入员工编号" v-model="form.userCode" maxlength="100" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="7">
                        <el-form-item label="所属部门：" prop="deptId">
                          <el-tree-select filterable v-model="form.deptId" :data="deptOptions" :props="{
                            value: 'id',
                            label: 'label',
                            children: 'children',
                          }" value-key="id" placeholder="请选择归属部门" check-strictly />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <!-- 个人信息第二行 -->
                    <el-row>
                      <el-col :span="5">
                        <el-form-item label="手机号码：" prop="phonenumber">
                          <el-input clearable placeholder="输入手机号码" v-model="form.phonenumber" maxlength="100" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="民族：" prop="nation">
                          <el-select clearable v-model="form.nation" placeholder="请选择民族">
                            <el-option v-for="dict in sys_nation" :key="parseInt(dict.value)" :label="dict.label"
                              :value="parseInt(dict.value)"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="身份证号：" prop="number">
                          <el-input clearable placeholder="请输入身份证号" v-model="form.number" maxlength="100" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="7">
                        <el-form-item label="入职时间：" prop="toDate">
                          <el-date-picker v-model="form.toDate" placeholder="请选择时间" type="datetime" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <!-- 个人信息第三行 -->
                    <el-row>
                      <el-col :span="5">
                        <el-form-item label="出生日期：" prop="birthday">
                          <el-date-picker v-model="form.birthday" type="date" placeholder="出生日期" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="政治面貌：" prop="zzml">
                          <el-select clearable v-model="form.zzml" placeholder="请选择政治面貌">
                            <el-option v-for="dict in sys_zzml" :key="parseInt(dict.value)" :label="dict.label"
                              :value="parseInt(dict.value)"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="办公电话：" prop="workPhone">
                          <el-input clearable placeholder="请输入办公电话" v-model="form.workPhone" maxlength="100" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="7">
                        <el-form-item label="房间号：" prop="room">
                          <el-input clearable placeholder="请输入房间号" v-model="form.room" maxlength="100" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <!-- 个人信息第四行 -->
                    <el-row>
                      <el-col :span="5">
                        <el-form-item label="婚姻状况：" prop="isMarry">
                          <el-select clearable v-model="form.isMarry" placeholder="请输入">
                            <el-option v-for="dict in sys_marry" :key="dict.value" :label="dict.label"
                              :value="parseInt(dict.value)" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="是否在编：" prop="isZb">
                          <el-select clearable v-model="form.isZb" placeholder="是否在编">
                            <el-option v-for="item in weave" :key="item.value" :label="item.label" :value="item.value" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="当前状态：" prop="workStatus">
                          <el-select clearable v-model="form.workStatus" placeholder="请输入状态">
                            <el-option v-for="item in work_status" :key="item.value" :label="item.label"
                              :value="parseInt(item.value)" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="7">
                        <el-form-item label="籍贯：" prop="jg">
                          <el-input clearable placeholder="请输入籍贯" v-model="form.jg" maxlength="100" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <!-- 个人信息第五行 -->
                    <el-row>
                      <el-col :span="5">
                        <el-form-item label="职务：" prop="zw">
                          <el-input clearable placeholder=" 请输入职务" v-model="form.zw" maxlength="100" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="技术职称：" prop="zc">
                          <el-select clearable v-model="form.zc" placeholder="请选择技术职称">
                            <el-option v-for="dict in sys_zc" :key="parseInt(dict.value)" :label="dict.label"
                              :value="parseInt(dict.value)"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="技术等级：" prop="level">
                          <el-select clearable v-model="form.level" placeholder="请选择技术等级" filterable>
                            <el-option v-for="dict in sys_level" :key="parseInt(dict.value)" :label="dict.label"
                              :value="parseInt(dict.value)" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="7">
                        <el-form-item label="评估时间：" prop="pgDate">
                          <el-date-picker v-model="form.pgDate" type="date" placeholder="请选择" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <!-- 个人信息第六行 -->
                    <el-row>
                      <el-col :span="5">
                        <el-form-item label="最高学历：" prop="maxXl">
                          <el-select clearable v-model="form.maxXl" placeholder="请选择学历" filterable>
                            <el-option v-for="dict in sys_xl" :key="parseInt(dict.value)" :label="dict.label"
                              :value="parseInt(dict.value)" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="学位：" prop="maxXw">
                          <el-select clearable v-model="form.maxXw" placeholder="请选择学位">
                            <el-option v-for="dict in sys_xw" :key="parseInt(dict.value)" :label="dict.label"
                              :value="parseInt(dict.value)" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="毕业院校：" prop="school">
                          <el-input clearable placeholder="请选择毕业院校" v-model="form.school" maxlength="100" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="7">
                        <el-form-item label="毕业时间：" prop="schoolDate">
                          <el-date-picker v-model="form.schoolDate" type="date" placeholder="请选择" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="所属小组：" prop="groupIds">
                      <el-select v-model="form.groupIds" multiple collapse-tags placeholder="请选择所属小组">
                        <el-option v-for="item in sys_user_group" :key="item.value" :label="item.label"
                          :value="parseInt(item.value)" />
                      </el-select>
                    </el-form-item>

                    <!-- 用户头像 -->
                    <user-basic-avatar ref="userBasicAvatarRef" class="user-basic-avatar" :userId="parseInt(form.userId)"
                      @getFileId="getFileId" @click="avatarShow" />
                    <!-- /用户头像 -->
                  </el-col>
                </el-row>

                <el-form-item label="备注：" prop="">
                  <el-input clearable resize="none" :rows="2" type="textarea" maxlength="500" show-word-limit />
                </el-form-item>
                <p class="pinformation">系统信息</p>
                <el-row>
                  <!-- 系统信息 -->
                  <el-col style="margin-top: 7px" :span="5">
                    <el-form-item label="用户账号：" prop="userName">
                      <el-input clearable v-model="form.userName" :rows="2" type="text" maxlength="100"
                        :disabled="form.userId ? true : false" />
                    </el-form-item>
                  </el-col>
                  <el-col style="margin-top: 7px" :span="19">
                    <el-row>
                      <el-col :span="16">
                        <el-form-item label="角色：" prop="roleIds">
                          <el-select v-model="form.roleIds" style="width: 100%" multiple filterable placeholder="请选择"
                            collapse-tags collapse-tags-tooltip :max-collapse-tags="5">
                            <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName"
                              :value="item.roleId" :disabled="item.status == 1"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="状态：" prop="status">
                          <el-row justify="center">
                            <el-radio v-model="form.status" :label="0">正常</el-radio>
                            <el-radio v-model="form.status" :label="1">停用</el-radio>
                          </el-row>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane label="教育工作经历" name="second">
            <educateWork v-if="activeName == 'second'" ref="son" :userId="form.userId" />
          </el-tab-pane>
          <el-tab-pane label="人员监督" name="third">Role</el-tab-pane>
          <el-tab-pane label="培训奖惩" name="fourth">Task</el-tab-pane>
          <el-tab-pane label="技术档案" name="fivth">Task</el-tab-pane>
          <el-tab-pane label="电子签名和人脸照片" name="signAndFace">
            <p class="pinformation">电子签名</p>
            <el-row :gutter="20">
              <el-col class="uploadStyle">
                <upLoadImage :userId="userId" :height="70" :typeId="21" />
              </el-col>
            </el-row>
            <p class="pinformation">人脸照片</p>
            <el-row :gutter="20">
              <el-col class="uploadStyle">
                <upLoadImage :height="120" :userId="userId" :typeId="22" />
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>
<script setup name="Newuser">
//引入的组件
import educateWork from "./educateWork.vue";
import {
  getTreeList,
  addUser,
  deptTreeSelect,
  getUser,
  updateUser,
  delUser,
  putResetPassword,
} from "@/api/system/newUser";
import upLoadImage from "./cnps/uploadImage.vue";
import userBasicAvatar from "./cnps/userBasicAvatar.vue";
import { nextTick } from "vue";

const { proxy } = getCurrentInstance();
const activeName = ref("first");
const {
  sys_zzml,
  sys_nation,
  sys_zc,
  sys_level,
  sys_xw,
  sys_xl,
  sys_marry,
} = proxy.useDict(
  "sys_zzml",
  "sys_nation",
  "sys_zc",
  "sys_level",
  "sys_xw",
  "sys_xl",
  "sys_marry",
);
const { sys_user_group } = proxy.useOrgDict(
  "sys_user_group"
);
const roleOptions = ref([]);
const son = ref(null);
const loading = ref(true);
const newUserTable = ref([]);
const total = ref();
const userId = ref();

const data = reactive({
  form: {
    sex: 1,
    currentState: 0,
    zzml: 1,
    degree: 1,
    maxDegree: 6,
    workStatus: 0,
    maxXl: 6,
    isMarry: 0,
    nation: 0,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workStatus: 0,
    dept: {},
  },
  rules: {
    nickName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    sex: [{ required: true, message: "性别不能为空", trigger: "blur" }],
    roleIds: [{ required: true, message: "角色不能为空", trigger: "blur" }],
    userName: [
      { required: true, message: "用户账号不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
    ],
    deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
    workStatus: [
      { required: true, message: "当前状态不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
const deptOptions = ref(undefined);
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    workStatus: 0,
    dept: {},
  };
  getList();
}

function addOrgId() {
  if (activeName.value !== "first") {
    activeName.value = "first";
  }
  nextTick(() => {
    proxy.$refs["userRef"].clearValidate();
    proxy.$refs["userBasicAvatarRef"].options.img = "";
    heightBright.value = "";
    form.value = {
      sex: 1,
      currentState: 0,
      zzml: 1,
      degree: 1,
      maxDegree: 6,
      workStatus: 0,
      maxXl: 6,
      isMarry: 0,
      nation: 0,
    };
  });
}

function rowClick(row) {
  activeName.value = "first";
  nextTick(() => {
    resetForm();
    proxy.$refs["userBasicAvatarRef"].options.img = "";
    proxy.$refs["userRef"].clearValidate();
    if (row.userType == 1) {
      getUser(row.userId).then((res) => {
        form.value = res.data;
        form.value.roleIds = res.roleIds;
        heightBright.value = row.userId;
      });
    }
  });
}
getUser().then((response) => {
  roleOptions.value = response.roles;
});
function resetForm() {
  proxy.resetForm("userRef");
}

//获取userTreetable的数据方法
function getList() {
  loading.value = true;
  getTreeList(queryParams.value).then((res) => {
    newUserTable.value = proxy.handleTree(res.data, "userId");
    total.value = res.data.length;
    loading.value = false;
  });
}

getList();

//搜索条件中 搜索方法
function handleQuery() {
  getList();
}

function listhandleDelete(row) {
  proxy.$modal
    .confirm("删除该人员将删除其关联所有数据，确定删除吗?点击确定后删除")
    .then(function () {
      return delUser(row.userId);
    })
    .then(() => {
      addOrgId();
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function avatarShow() {
  addsava(true).then((res) => {
    proxy.$refs["userBasicAvatarRef"].editCropper("show");
  });
}

//机构列表中保存 成员
function addsava(isAuto) {
  return new Promise((resolve, reject) => {
    proxy.$refs["userRef"].validate((valid) => {
      if (valid) {
        if (form.value.userId) {
          updateUser(form.value)
            .then((response) => {
              if (!isAuto) {
                proxy.$modal.msgSuccess("修改成功");
              }
              open.value = false;
              getList();
              resolve();
            })
            .catch(() => {
              reject();
            });
        } else {
          addUser(form.value)
            .then((response) => {
              if (!isAuto) {
                proxy.$modal.msgSuccess("新增成功");
              }
              form.value.userId = response.data;
              heightBright.value = response.data;
              open.value = false;
              resetQuery();
              getList();
              resolve();
            })
            .catch(() => {
              reject();
            });
        }
      }
    });
  });
}

//右侧新增
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}
getDeptTree();
const weave = [
  {
    value: 1,
    label: "是",
  },
  {
    value: 0,
    label: "否",
  },
];

//当前状态
const work_status = ref([]);
work_status.value = [
  {
    value: 0,
    label: "在职",
  },
  {
    value: 1,
    label: "离职",
  },
];
//性别
const sex = ref([]);
sex.value = [
  {
    value: 1,
    label: "男",
  },
  {
    value: 0,
    label: "女",
  },
];

const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

function tabChange(name) {
  if (name === "signAndFace") {
    userId.value = form.value.userId;
  }
}

async function leaveTab(activeName, oldActiveName) {
  if (oldActiveName == "first" && activeName !== "first") {
    return addsava(true).catch((res) => {
      return false;
    });
  }
}

const heightBright = ref("");
function tableRowClass({ row }) {
  if (row) {
    if (row.userId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}

function resetPassword(row) {
  proxy.$modal
    .confirm("确定为" + row.nickName + "重置密码吗？")
    .then(function () {
      putResetPassword(row.userId).then((res) => {
        proxy.$modal.alert(
          "“" + row.nickName + "”" + "密码已重置为：" + res.data,
          "Title",
          {}
        );
      });
    });
}

function getFileId(val) {
  form.value.avatar = val;
  addsava(true);
}
</script>

<style scoped lang="scss">
.uploadStyle {
  padding: 20px 0;
}

.user-basic-avatar {
  margin-left: 100px;
  margin-top: 30px;
}
</style>
